/* 
 * Quechua - the lightweight data mining framework
 *
 * Copyright (C) 2012 Marek Denis <quechua@octogan.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef THREADS_H
#define	THREADS_H

#include <unistd.h>
#include <ev++.h>
#include "log.h"
#include "types.h"
#include "workflow.h"

struct command_s {
    datapack_ptr data;
    void *object;
    thread_func_ptr function;
    STEP step;
    Workflow* flow;
};

typedef std::shared_ptr<command_s> command_ptr;
typedef std::queue<command_ptr> queue_cmd_t;

class Thread : public sigc::trackable {
 public:
     Thread(command_ptr command_) : command(command_) {
         LOG(DEBUG) << "Initializing Thread object at: " << this;
     }
     virtual ~Thread();
 
     void run();
 private:
     command_ptr command;
     void finish(command_ptr cmd);
};

class Threads {
 public:
     
     Threads();
     Threads(int threads_num_);
     virtual ~Threads();
 
     void prepare();
     void start();
     void stop();
 
     void RUN_IN_THREAD(datapack_ptr data, void* object, 
                        Workflow* flow,
                        thread_func_ptr function);
 
     //other threads can safely call this method, putting some results.
     //This will call the async watcher and will make the workflow to step in
     //it's process
     void handle_command(command_ptr cmd);
 
 private:    
     queue_cmd_t cmds;
     g_mutex mutex;
     g_threadpool *pool;
     ev::async cmd_watcher;
 
     void handle_command_cb(ev::async &watcher, int revents);
     int calculate_threads_number();
};

#endif	/* THREADS_H */

